package org.samples.web;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.samples.model.ExamUser;
import org.samples.service.ITeacherService;
import org.samples.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class LoginController {
	
	@Autowired
	private ITeacherService teacherService;
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String toLogin(Model model, HttpSession session){
		session.removeAttribute("user");
		model.addAttribute("userModel", new ExamUser());
		return "login/login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String doLogin(Model model, ExamUser user, HttpSession session, RedirectAttributes redirectAttributes) throws Exception{
		if(user != null){
			ExamUser resultUser = teacherService.getByUserName(user.getUserName());
			if(resultUser != null){
				if(resultUser.getPassword() != null){
					String encodePassword = MD5Utils.getMD5Code(user.getPassword());
					Date currentTime = null;
					Date lastLockTime = resultUser.getLastLockTime();
					Calendar currentTimeCalendar = Calendar.getInstance();
					currentTimeCalendar.setTime(new Date());
					currentTimeCalendar.add(Calendar.MINUTE, -5);
					currentTime = currentTimeCalendar.getTime();
					if(lastLockTime.before(currentTime)){
						if(encodePassword.equals(resultUser.getPassword())){
							resultUser.setLoginFailCount(0);
							teacherService.editUser(resultUser);
							session.setAttribute("user", resultUser);
							if(resultUser.getExamUserRole().getRole().getRoleId() == 2 || resultUser.getExamUserRole().getRole().getRoleId() == 1){
								return "redirect:/teacher/toManageStudent";
							}else{
								return "redirect:/student/subjects";
							}
						}else{
							resultUser.setLoginFailCount(resultUser.getLoginFailCount() + 1);
							if(resultUser.getLoginFailCount() >= 3){
								resultUser.setLoginFailCount(0);
								resultUser.setLastLockTime(new Date());
								teacherService.editUser(resultUser);
							}
							teacherService.editUser(resultUser);
							redirectAttributes.addFlashAttribute("message", "用户名或密码错误");
							return "redirect:/login";
						}
					}else{
						redirectAttributes.addFlashAttribute("message", "账户被锁定，请稍后再登录");
						return "redirect:/login";
					}
				}
			}
		}
		redirectAttributes.addFlashAttribute("message", "用户名或密码错误");
		return "redirect:/login";
	}
	
}
